﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using Kooboo.HtmlFunc;
using Kooboo.HtmlFunc.Providers;

namespace Kooboo.CMS.SiteConverter.Parser.Razor
{
    public class LabelParser : ParserBase, IParser<ILabel>
    {
        public static string DoubleQuotesEncode(string input)
        {
            if (string.IsNullOrEmpty(input)) { return input; }
            else { return input.Replace("\"", "\"\""); }
        }

        public static string GetInnerText(ILabel label)
        {
            var innerHtml = NodeExtension.GetInnerContent(label.StartNode, label.EndNode);
            return DoubleQuotesEncode(innerHtml);
        }

        public static string GetLabelKey(ILabel label)
        {
            return string.IsNullOrEmpty(label.Key) ? (string.Empty) : ("@\"" + DoubleQuotesEncode(label.Key) + "\"");
        }

        public static void ReplateInner(ILabel label, HtmlNode inner)
        {
            NodeExtension.ReplaceInner(label.StartNode, label.EndNode, inner);

            if (ParserSetting.RemoveFuncMarkers)
            {
                if (label.StartNode == label.EndNode)
                {
                    // attribute mode is obsoleted
                }
                else
                {
                    label.EndNode.RemoveWithPrevWhitespace();
                    label.StartNode.ParentNode.RemoveChild(label.StartNode);
                }
            }
        }

        #region IParser<ILabel> Members

        public void Parse(ILabel obj)
        {
            var markup = string.Format("@(@\"{0}\".Label({1}))", GetInnerText(obj), GetLabelKey(obj));
            var markupNode = NodeExtension.CreateNode(markup);
            ReplateInner(obj, markupNode);
        }

        #endregion
    }
}
